package www.yingdi365.com.fragment;


import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.jude.easyrecyclerview.EasyRecyclerView;
import com.jude.easyrecyclerview.adapter.BaseViewHolder;
import com.jude.easyrecyclerview.adapter.RecyclerArrayAdapter;
import com.jude.easyrecyclerview.decoration.SpaceDecoration;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.HttpHeaders;

import java.util.HashMap;
import java.util.List;

import okhttp3.Call;
import okhttp3.Response;
import www.yingdi365.com.R;
import www.yingdi365.com.base.ZjbBaseFragment;
import www.yingdi365.com.constant.Constant;
import www.yingdi365.com.model.AppECardTmpl;
import www.yingdi365.com.model.AppECardTmplPaging;
import www.yingdi365.com.model.OkObject;
import www.yingdi365.com.util.DpUtils;
import www.yingdi365.com.util.GsonUtils;
import www.yingdi365.com.util.LogUtil;
import www.yingdi365.com.viewholder.HeKaViewHolder;

/**
 * A simple {@link Fragment} subclass.
 */
public class HeKaFragment extends ZjbBaseFragment implements SwipeRefreshLayout.OnRefreshListener {

    private View mInflate;
    private EasyRecyclerView recyclerView;
    private RecyclerArrayAdapter<AppECardTmpl> adapter;
    private int page = 0;
    private String type;

    public HeKaFragment() {
        // Required empty public constructor
    }

    public HeKaFragment(String type) {
        this.type = type;
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        if (mInflate == null) {
            mInflate = inflater.inflate(R.layout.fragment_he_ka, container, false);
            init();
        }
        //缓存的rootView需要判断是否已经被加过parent， 如果有parent需要从parent删除，要不然会发生这个rootview已经有parent的错误。
        ViewGroup parent = (ViewGroup) mInflate.getParent();
        if (parent != null) {
            parent.removeView(mInflate);
        }
        return mInflate;
    }

    @Override
    protected void initIntent() {

    }

    @Override
    protected void initSP() {

    }

    @Override
    protected void findID() {
        recyclerView = (EasyRecyclerView) mInflate.findViewById(R.id.recyclerView);
    }

    @Override
    protected void initViews() {
        initRecycle();
    }

    @Override
    protected void setListeners() {

    }

    @Override
    protected void initData() {
        onRefresh();
    }

    private void initRecycle() {
//        recyclerView.setLayoutManager(new StaggeredGridLayoutManager(2,StaggeredGridLayoutManager.VERTICAL));
        GridLayoutManager gridLayoutManager = new GridLayoutManager(getActivity(), 2);
        recyclerView.setLayoutManager(gridLayoutManager);
        SpaceDecoration itemDecoration = new SpaceDecoration((int) DpUtils.convertDpToPixel(1, getActivity()));
        itemDecoration.setPaddingEdgeSide(true);
        itemDecoration.setPaddingStart(true);
        recyclerView.addItemDecoration(itemDecoration);
        int red = getResources().getColor(R.color.basic_color);
        recyclerView.setRefreshingColor(red);
        recyclerView.setAdapterWithProgress(adapter = new RecyclerArrayAdapter<AppECardTmpl>(getActivity()) {
            @Override
            public BaseViewHolder OnCreateViewHolder(ViewGroup parent, int viewType) {
                int layout = R.layout.item_qingjian;
                return new HeKaViewHolder(parent, layout);
            }

        });
        adapter.setMore(R.layout.view_more, new RecyclerArrayAdapter.OnMoreListener() {
            @Override
            public void onMoreShow() {
                OkObject okObject = getOkObject();
                OkGo.post(okObject.getUrl())//
                        .tag(this)//
                        .headers(okObject.getHeaders())
                        .upJson(okObject.getJson())//
                        .execute(new StringCallback() {
                            @Override
                            public void onSuccess(String s, Call call, Response response) {
                                try {
                                    LogUtil.LogShitou("QingJianFragment--onSuccess", "更多请柬查询" + s);
                                    page++;
                                    AppECardTmplPaging appECardTmplPaging = GsonUtils.parseJSON(s, AppECardTmplPaging.class);
                                    List<AppECardTmpl> appECardTmplPagingTmpls = appECardTmplPaging.getTmpls();
                                    adapter.addAll(appECardTmplPagingTmpls);
                                } catch (Exception e) {
                                    adapter.pauseMore();
                                }
                            }

                            @Override
                            public void onError(Call call, Response response, Exception e) {
                                super.onError(call, response, e);
                                if (response != null) {
                                    if (response.code() == 401) {
                                        showReLoginDialog();
                                    }
                                }
                                adapter.pauseMore();
                            }
                        });
            }

            @Override
            public void onMoreClick() {

            }
        });
        adapter.setNoMore(R.layout.view_nomore_qingjian);
        adapter.setError(R.layout.view_error, new RecyclerArrayAdapter.OnErrorListener() {
            @Override
            public void onErrorShow() {
                adapter.resumeMore();
            }

            @Override
            public void onErrorClick() {
                adapter.resumeMore();
            }
        });
        recyclerView.setRefreshListener(this);
        adapter.setOnItemClickListener(new RecyclerArrayAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
//                Intent intent = new Intent();
//                intent.setClass(getActivity(), ShangPinXQActivity.class);
//                startActivity(intent);
            }
        });
    }

    @Override
    public void onRefresh() {
        page = 0;
        OkObject okObject = getOkObject();
        OkGo.post(okObject.getUrl())//
                .tag(this)//
                .headers(okObject.getHeaders())
                .upJson(okObject.getJson())//
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        LogUtil.LogShitou("请柬查询", s);
                        try {
                            AppECardTmplPaging appECardTmplPaging = GsonUtils.parseJSON(s, AppECardTmplPaging.class);
                            List<AppECardTmpl> appECardTmplPagingTmpls = appECardTmplPaging.getTmpls();
                            page++;
                            adapter.clear();
                            adapter.addAll(appECardTmplPagingTmpls);
                        } catch (Exception e) {
                            showError(getResources().getString(R.string.shujuchucuo));
                        }
                    }

                    @Override
                    public void onError(Call call, Response response, Exception e) {
                        super.onError(call, response, e);
                        if (response != null) {
                            if (response.code() == 401) {
                                showReLoginDialog();
                            }
                        }
                        showError(getResources().getString(R.string.wangluochucuo));
                    }

                    public void showError(String msg) {
                        View view_loaderror = LayoutInflater.from(getActivity()).inflate(R.layout.view_loaderror, null);
                        TextView textMsg = (TextView) view_loaderror.findViewById(R.id.textMsg);
                        textMsg.setText(msg);
                        view_loaderror.findViewById(R.id.buttonReLoad).setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                initData();
                            }
                        });
                        recyclerView.setErrorView(view_loaderror);
                        recyclerView.showError();
                    }
                });
    }

    private OkObject getOkObject() {
        String url = Constant.HOST + Constant.Url.AppECardTmplService + "query" + "?page=" + page + "&page_size=10";
        HttpHeaders headers = new HttpHeaders();
        headers.put(Constant.TOKEN, appLoginResult.getToken());
        HashMap<String, String> params = new HashMap<>();
        params.put("type", type);
        return new OkObject(headers, params, url);
    }

}
